if [ $# -eq 0 ]
  then
    echo "No arguments supplied"
    exit 1
fi

if [ ! -d configs ]; then
  echo "Creating config folder...";
  mkdir configs;
fi

DIRNAME=$1;
if [ ! -d configs/$DIRNAME ]; then
  echo "Creating $DIRNAME config folder...";
  mkdir configs/$DIRNAME;
else
  echo "folder configs/$DIRNAME exists"
  exit 1
fi

source load-dotenv.sh;

PROJECT_DIR=$PWD

cd configs/$DIRNAME;

wg genkey | tee privatekey | wg pubkey > publickey;

USED_IPS=$(cat ${PROJECT_DIR}/${WG_ROOT_CONFIG_FOLDER}/wg0.conf | grep AllowedIPs | cut -d '=' -f2 | cut -d '/' -f1 | cut -d '.' -f4)
START_IP=10
CUR_IP=$START_IP

contains() {
	[[ "$1" =~ (^|[[:space:]])"$2"($|[[:space:]]) ]] && echo 'yes' || echo 'no'
}
while [[ `contains "$USED_IPS" "$CUR_IP"` == 'yes' ]]
do
	echo $CUR_IP is used
	CUR_IP=$((CUR_IP+1))
done
export ROOT_PUBKEY=$(cat ${PROJECT_DIR}/${WG_ROOT_CONFIG_FOLDER}/publickey)
echo current ip:  192.168.100.$CUR_IP
echo "$DIRNAME.conf"
echo "[Interface]
PrivateKey = $(cat privatekey)
Address = $WG_SUBNET_PREFIX.$CUR_IP/24 # 内网IP地址

[Peer]
PublicKey = ${ROOT_PUBKEY}
Endpoint = ${WG_SERVER_IP}:${WG_PORT}       #中继节点IP:端口
AllowedIPs = ${WG_SUBNET_PREFIX}.0/24
PersistentKeepalive = 30" > "$DIRNAME.conf"


echo "
[Peer]
PublicKey = $(cat publickey)
AllowedIPs = ${WG_SUBNET_PREFIX}.$CUR_IP/32
" >> ${PROJECT_DIR}/${WG_ROOT_CONFIG_FOLDER}/wg0.conf

echo "configured...\n"
cat  "${PROJECT_DIR}/${WG_ROOT_CONFIG_FOLDER}/wg0.conf"
cd ../..;
